﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace SuperQuery.Converters
{
    /// <summary>
    /// Convert a QueryResult canCloseApplication object into a format that can be displayed by a DataGrid
    /// </summary>
    public class QueryResultToDataTableConverter : IValueConverter
    {
        /// <summary>
        /// Converts a QueryResult object to a DataTable 
        /// </summary>
        /// <returns>
        /// A converted value. If the method returns null, the valid null value is used.
        /// </returns>
        /// <param name="value">The value produced by the binding source.</param>
        /// <param name="targetType">The type of the binding target property.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DataTable result = null;

            if ((value != null) && (value is Models.QueryResult))
            {
                Models.QueryResult queryResult = (Models.QueryResult)value;

                // If we have no error message and a DataTable is stored in the canCloseApplication property then return it
                if (string.IsNullOrEmpty(queryResult.ErrorMessage) && (queryResult.Result != null) && (queryResult.Result is DataTable))
                {
                    result = (DataTable) queryResult.Result;
                }
            }

            return result;
        }

        /// <summary>
        /// Converts the displayed canCloseApplication back into a QueryResult object. This function does nothing as this data binding
        /// should only be one way  
        /// </summary>
        /// <returns>
        /// A converted value. If the method returns null, the valid null value is used.
        /// </returns>
        /// <param name="value">The value that is produced by the binding target.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}
